<template>
	<view class="order-ready">
		<view class="order-ready-send address-card" @click="selectAddress('send')">
			<view class="send-icon">
				取
			</view>
			<view class="address-detail">
				<u--text :text="addressText1('send')" size="16" align="center" class="u-flex-y-center"></u--text>
				<u--text v-if="addressText2('send')" type="info" margin="8rpx 0 0 0" :text="addressText2('send')"
					size="14" align="center"></u--text>
			</view>
			<view class="address-edit">
				<u-icon name="edit-pen" color="#909193" size="28"></u-icon>
			</view>
		</view>
		<u-gap height="30rpx"></u-gap>
		<view class="order-ready-send address-card" @click="selectAddress('back')">
			<view class="back-icon">
				送
			</view>
			<view class="address-detail">
				<u--text :text="addressText1('back')" size="16" align="center" class="u-flex-y-center"></u--text>
				<u--text v-if="addressText2('back')" type="info" margin="8rpx 0 0 0" :text="addressText2('back')"
					size="14"></u--text>
			</view>
			<view class="address-edit">
				<u-icon name="edit-pen" color="#909193" size="28"></u-icon>
			</view>
		</view>
		<u-gap height="30rpx"></u-gap>

		<view class="dy-card">
			<view class="dy-card-row" @click="showTimePicker = true">
				<view class="primary-text">
					预约取件时间
				</view>

				<picker @columnchange="dateColumnChange" @change="bindPickerChange" mode="multiSelector"
					:value="dateIndex" :range="dateList">
					<view class="uni-input">{{formatterDataInfo.text}}</view>
				</picker>
			</view>
		</view>
		<u-gap height="30rpx"></u-gap>
		<view class="dy-card">
			<view class="">
				<textarea :value="note" placeholder="请输入备注" name="" id="" cols="30" rows="5"></textarea>
			</view>
		</view>
		<view class="bottom-bar flex-primary" :style="bottomBarStyle">
			<view class="bottom-bar-btn" @click="debounceBuyHandle">
				立即购买
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				goodId: '',
				dateIndex: [0, 0],
				sendAddress: {
					userName: '',
					telNumber: '',
				},
				note: '',
				backAddress: {
					userName: '',
					telNumber: '',
				},
				addressType: 'send',
				showTimePicker: false,
				selectDate: null,
				goodInfo: {},
				paying: false
			}
		},
		computed: {
			bottomBarStyle() {
				const styleObj = {
					bottom: this.systemInfo.safeAreaInsets.bottom + 'px'
				}
				return uni.$u.addStyle(styleObj, 'string')
			},
			addressData() {
				return (type) => type == 'send' ? this.sendAddress : this.backAddress
			},
			addressText1() {
				return (type) => {
					const {
						userName,
						telNumber
					} = this.addressData(type)
					if (!userName) {
						return '请选择地址'
					}
					return `${userName} - ${telNumber}`
				}
			},
			addressText2() {
				return (type) => {
					const {
						provinceName,
						cityName,
						countyName,
						detailInfo
					} = this.addressData(type)
					if (!provinceName) {
						return ''
					}
					return `${provinceName}${cityName}${countyName}${detailInfo}`
				}
			},
			formatterDataInfo() {
				const dateIndex = this.dateIndex[0]
				const timeIndex = this.dateIndex[1]
				const date = this.dateList[0][dateIndex]
				const time = this.dateList[1][timeIndex]
				const startTime = time.split('~')[0] + ':00'
				const endTime = time.split('~')[1] + ':00'
				return {
					start: `${date} ${startTime}`,
					end: `${date} ${endTime}`,
					text: `${date} ${time}`
				}
			},
			dateList() {
				const now = new Date();
				const dates = [];
				const times = [];
				let startDayOffset = 0;

				// Check if we should start from tomorrow instead of today
				if (now.getHours() >= 17) {
					startDayOffset = 1;
				}

				// Generate dates for the next 7 days starting from today or tomorrow
				for (let i = startDayOffset; i < 7 + startDayOffset; i++) {
					const date = new Date(now.getTime() + i * 24 * 60 * 60 * 1000);
					dates.push(this.formatDate(date));
				}

				// Generate time slots from 09:00 to 18:00
				for (let hour = 9; hour <= 19; hour = hour+2) {
					const nextHour = hour+1
					const startTime = `${hour < 10 ? '0' + hour : hour}:00`;
					const endTime = `${nextHour < 10 ? '0' + nextHour : nextHour}:59`;

					// Check if selected date is today and adjust based on current time
					const currentDate = this.selectDate || dates[0]
					if (currentDate === this.formatDate(now)) {
						if (hour < now.getHours() + 1) {
							// Skip if it's before current hour on the same day
							continue;
						}
						if (hour >= 19) {
							// Stop adding if it's after 19:00 on the same day
							break;
						}
					} else if (hour === 9 && now.getHours() > 9) {
						// Skip if it's before current hour on a different day
						continue;
					}

					times.push(`${startTime}~${endTime}`);
				}

				return [dates, times];
			}
		},
		onLoad(options) {
			this.goodId = options.goodId
		},
		onShow() {
			this.loadDetail()
		},
		methods: {
			loadDetail() {
				this.$u.api['goods/findGoodsDetail']({
					goodsMallId: this.goodId
				}).then(res => {
					this.goodInfo = res.data.data.goodsMall
				})
			},
			dateColumnChange(val) {
				const {
					column,
					value
				} = val.detail
				if (column == 0) {
					this.selectDate = this.dateList[0][value]
				}
			},
			bindPickerChange(val) {
				this.dateIndex = val.detail.value
			},

			checkParams() {
				let errMsg = ''
				if (this.dateIndex.length < 2) {
					errMsg = '请选择预约时间'
				}
				if (!this.addressText2('back')) {
					errMsg = '请选择送回地址'
				}
				if (!this.addressText2('send')) {
					errMsg = '请选择取衣地址'
				}
				if (errMsg) {
					uni.showToast({
						title: errMsg,
						icon: 'none'
					})
					return false
				} else {
					return true
				}

			},
			debounceBuyHandle() {
				uni.$u.debounce(this.buyHandle, 200)
			},
			buyHandle() {
				const pass = this.checkParams()
				if (!pass) {
					return
				}
				if (this.paying) {
					return
				}
				this.paying = true
				const params = {
					goodsList: [{
						quantity: 1, // 购买数量 必填
						price: Number(this.goodInfo.price) * 100, // 商品价格 必填

						goodsName: this.goodInfo.goodsName, // 商品名称 必填
						goodsPhoto: this.goodInfo.goodsName,
						goodsId: this.goodInfo.dyItemId, // 商品ID 必填
						goodsType: 1, // 商品类型 必填

						goodsLabels: [], // 商品标签 非必填
						dateRule: "", // 使用规则 非必填
					}, ],
					payment: {
						totalAmount:Number(this.goodInfo.price) * 100, // 订单总价 必填
					},
					contactInfo: {
						phoneNumber: this.sendAddress.phoneNumber, // 手机号 非必传
						contactName: this.sendAddress.userName, // 姓名 非必传
					},
					note: this.note, // 备注 非必传

					storeInfo: {
						storeName: "", // 商店名称 非必传
						storeIcon: ''
					},
					callbackData: {}, // 透传数据，开发者自定义字段 非必传
					tradeOption: {
						life_trade_flag: 1 // 0：非融合链路（默认值）  1：走融合链路（标准融合/完全融合）
					}, // 透传数据，开发者自定义字段 非必传
				}
				tt.createOrder({
					...params,
					success: (res) => {
						const {
							orderId,
							outOrderNo
						} = res;
						this.updateOrderData(outOrderNo)
					},
					fail: (res) => {
						const {
							orderId,
							outOrderNo,
							errNo,
							errMsg,
							errLogId
						} = res;
						// 预下单失败
						if (errLogId) {
							console.log("预下单失败", errNo, errMsg, errLogId);
						}
						// 支付失败
						if (orderId || outOrderNo) {
							this.updateOrderData(outOrderNo)
						}
					},
					complete: () => {
						this.paying = false
					}
				});
			},
			updateOrderData(mallOrderId) {
				const params = {
					mallOrderId,
					
					backAddress: this.backAddress.detailInfo,
					backCity: this.backAddress.cityName,
					backCounty: this.backAddress.countyName,
					backMan: this.backAddress.userName,
					backPhone: this.backAddress.telNumber,
					backProvince: this.backAddress.provinceName,
					
					takeAddress: this.sendAddress.detailInfo,
					takeCity: this.sendAddress.cityName,
					takeCounty: this.sendAddress.countyName,
					takeProvince: this.sendAddress.provinceName,
					takeMan: this.sendAddress.userName,
					takePhone: this.sendAddress.telNumber,
					
					takePreTimeStart: this.formatterDataInfo.start,
					takePreTimeEnd: this.formatterDataInfo.end,
				}
				
				this.$u.api['order/updateOrder'](params).then(res => {
					uni.navigateTo({
						url: '/pages/order/detail/detail?mallOrderId=' + mallOrderId
					})
				})
				
			},
			selectAddress(type) {
				this.addressType = type
				uni.chooseAddress({
					success: (res) => {
						if (this.addressType == 'send') {
							this.sendAddress = res
							if (!this.backAddress.userName) {
								this.backAddress = res
							}
						} else {
							this.backAddress = res
						}
					},
					fail(err) {
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.address-card {}

	.bottom-bar {
		position: fixed;
		width: 100vw;
		justify-content: center;

		&-btn {
			padding: 0 15rpx;
			width: 620rpx;
			background-color: $u-error;
			color: $u-error-light;
			border-radius: 40rpx;
			text-align: center;
			cursor: pointer;
			border: none;
			height: 90rpx;
			line-height: 90rpx;
			box-sizing: border-box;
		}
	}
</style>